<template>
  <div class="warehouse-receiving">
    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-item">
          <label>货物名称</label>
          <input 
            v-model="searchForm.goodName" 
            type="text" 
            placeholder="请输入货物名称"
            class="form-input"
          />
        </div>
        
        <div class="form-item">
          <label>条件查询材质</label>
          <select 
            v-model="searchForm.materialId" 
            class="form-select"
            :disabled="loadingMaterials"
          >
            <option value="">请选择材质</option>
            <option 
              v-for="material in materialOptions" 
              :key="material.id" 
              :value="material.id"
            >
              {{ material.materialName }}
            </option>
          </select>
          <div v-if="loadingMaterials" class="loading-hint">正在加载材质数据...</div>
        </div>
        
        <div class="form-item">
          <label>产地</label>
          <input 
            v-model="searchForm.placeofOrigin" 
            type="text" 
            placeholder="请输入产地"
            class="form-input"
          />
        </div>
        
        <div class="form-item">
          <label>支付方式</label>
          <input 
            v-model="searchForm.payway" 
            type="text" 
            placeholder="请输入支付方式"
            class="form-input"
          />
        </div>
        
        <div class="form-item">
          <label>登记人</label>
          <input 
            v-model="searchForm.registrant" 
            type="text" 
            placeholder="请输入登记人"
            class="form-input"
          />
        </div>
        
        <div class="form-actions">
          <button @click="handleSearch" class="btn btn-primary">
            <i class="icon-search"></i>
            查询
          </button>
          <button @click="handleReset" class="btn btn-secondary">
            <i class="icon-refresh"></i>
            重置
          </button>
        </div>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <button @click="handleAdd" class="btn btn-primary">
        新增
      </button>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <table class="data-table">
        <thead>
          <tr>
            <th>货物名称</th>
            <th>类型</th>
            <th>材质</th>
            <th>规格</th>
            <th>产地</th>
            <th>数量</th>
            <th>单价</th>
            <th>支付方式</th>
            <th>采购金额</th>
            <th>登记人</th>
            <th>备注</th>
            <th>创建时间</th>
            <th>操作</th>
            <!-- 隐藏的swNo列 -->
            <th style="display: none;">swNo</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="14" class="loading-cell">
              <div class="loading-spinner">加载中...</div>
            </td>
          </tr>
          <tr v-else-if="tableData.length === 0">
            <td colspan="14" class="empty-cell">
              暂无数据
            </td>
          </tr>
          <tr v-else v-for="(item, index) in tableData" :key="item.id">
            <td>{{ item.goodName }}</td>
            <td>{{ item.typeName || '-' }}</td>
            <td>{{ item.materialName || item.materialid }}</td>
            <td>{{ item.specification }}</td>
            <td>{{ item.placeofOrigin }}</td>
            <td>{{ item.quantity }}</td>
            <td>{{ formatAmount(item.unitPrice) }}</td>
            <td>{{ item.payway }}</td>
            <td>{{ formatAmount(item.purchaseAmount) }}</td>
            <td>{{ item.registrant }}</td>
            <td>{{ item.remark || '-' }}</td>
            <td>{{ formatDate(item.createdTime) }}</td>
            <td>
              <div class="action-buttons">
                <button @click="handleEdit(item)" class="btn-action btn-edit">编辑</button>
                <button @click="handleDeleteItem(item)" class="btn-action btn-delete">删除</button>
                <button @click="handleView(item)" class="btn-action btn-view">查看</button>
              </div>
            </td>
            <!-- 隐藏的swNo列 -->
            <td style="display: none;">{{ item.swNo || '-' }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <div class="pagination-info">
        共{{ totalPages }}页/{{ totalRecords }}条数据
      </div>
      <div class="pagination-controls">
        <button 
          @click="goToPage(currentPage - 1)" 
          :disabled="currentPage === 1"
          class="btn-pagination"
        >
          &lt;
        </button>
        
        <button 
          v-for="page in visiblePages" 
          :key="page"
          @click="goToPage(page)"
          :class="['btn-pagination', { active: page === currentPage }]"
        >
          {{ page }}
        </button>
        
        <button 
          v-if="showEllipsis"
          class="btn-pagination disabled"
        >
          ...
        </button>
        
        <button 
          v-if="showLastPage"
          @click="goToPage(totalPages)"
          :class="['btn-pagination', { active: currentPage === totalPages }]"
        >
          {{ totalPages }}
        </button>
        
        <button 
          @click="goToPage(currentPage + 1)" 
          :disabled="currentPage === totalPages"
          class="btn-pagination"
        >
          &gt;
        </button>
      </div>
      
      <div class="pagination-jump">
        <span>跳至</span>
        <input 
          v-model="jumpToPage" 
          type="number" 
          min="1" 
          :max="totalPages"
          @keyup.enter="handleJumpToPage"
          class="jump-input"
        />
        <span>页</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { materialApi } from '@/api'
const router = useRouter()
// 定义接口类型
interface WarehouseReceivingItem {
  id: number
  swNo: string  // 添加swNo字段
  goodName: string
  payway: string
  typeId: number
  materialid: number
  specification: string
  placeofOrigin: string
  address: string
  quantity: number
  unitPrice: number
  remark: string
  purchaseAmount: number
  registrant: string
  createdTime: string
  materialName: string | null
  typeName: string | null
  selected?: boolean
}

interface ApiResponse {
  code: number
  message: string
  data: {
    totalCount: number
    totalPage: number
    data: WarehouseReceivingItem[]
  }
}

// 搜索表单数据 - 根据API接口字段调整
const searchForm = reactive({
  goodName: '',
  materialId: '',
  placeofOrigin: '',
  payway: '',
  registrant: ''
})

// 材质数据
const materialOptions = ref<Array<{id: number, materialName: string}>>([])
const loadingMaterials = ref(false)

// 表格数据
const tableData = ref<WarehouseReceivingItem[]>([])
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(2)
const totalPages = ref(0)
const totalRecords = ref(0)
const jumpToPage = ref(1)

// 移除全选状态
// const selectAll = ref(false)

// 计算属性
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, start + 4)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

const showEllipsis = computed(() => {
  return totalPages.value > 5 && currentPage.value < totalPages.value - 2
})

const showLastPage = computed(() => {
  return totalPages.value > 5 && currentPage.value < totalPages.value - 2
})

// 获取仓库收货列表数据
const fetchReceivingList = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = {
      PageIndex: currentPage.value,
      PageSize: pageSize.value,
      ...(searchForm.goodName && { GoodName: searchForm.goodName }),
      ...(searchForm.materialId && { MaterialId: parseInt(searchForm.materialId) }),
      ...(searchForm.placeofOrigin && { PlaceofOrigin: searchForm.placeofOrigin }),
      ...(searchForm.payway && { Payway: searchForm.payway }),
      ...(searchForm.registrant && { Registrant: searchForm.registrant })
    }

    // 调用封装的API方法
    const response = await materialApi.getWarehouseReceivingList(params)

    if (response.code === 200) {
      const { data } = response.data
      console.log('API响应数据结构:', data)
      
      // 安全检查数据结构
      if (data && Array.isArray(data.data)) {
        tableData.value = data.data.map((item: any) => ({
          ...item,
          selected: false
        }))
        totalRecords.value = data.totalCount || 0
        totalPages.value = data.totalPage || 0
      } else if (Array.isArray(data)) {
        // 如果data直接是数组
        tableData.value = data.map((item: any) => ({
          ...item,
          selected: false
        }))
        totalRecords.value = data.length
        totalPages.value = Math.ceil(data.length / pageSize.value)
      } else {
        console.warn('意外的数据结构:', data)
        tableData.value = []
        totalRecords.value = 0
        totalPages.value = 0
      }
    } else {
      throw new Error(response.message || '获取数据失败')
    }
    
  } catch (error) {
    console.error('获取数据出错:', error)
    // 如果API调用失败，使用模拟数据
    const mockData: WarehouseReceivingItem[] = [
      {
        id: 2,
        swNo: 'WR20250917001',  // 确保有swNo字段
        goodName: "高强度螺栓",
        payway: "银行转账",
        typeId: 3,
        materialid: 10086,
        specification: "M12×80mm 8.8级",
        placeofOrigin: "上海市",
        address: "工业园区A区3号楼仓库",
        quantity: 500,
        unitPrice: 12.5,
        remark: "用于生产线设备维护",
        purchaseAmount: 6250,
        registrant: "张明",
        createdTime: "2025-09-17T07:56:49.607",
        materialName: null,
        typeName: null,
        selected: false
      }
    ]
    
    tableData.value = mockData
    totalRecords.value = 1
    totalPages.value = 1
    
    alert('获取数据出错，已显示模拟数据')
  } finally {
    loading.value = false
  }
}

// 获取材质数据
const fetchMaterials = async () => {
  try {
    loadingMaterials.value = true
    const response = await materialApi.getMaterials()
    
    if (response && response.code === 200 && response.data) {
      materialOptions.value = response.data
    } else {
      console.error('获取材质数据失败:', response?.message)
      // 如果API失败，使用默认数据
      materialOptions.value = [
        { id: 1, materialName: '金属' },
        { id: 2, materialName: '橡胶' },
        { id: 3, materialName: '塑料' },
        { id: 4, materialName: '液体' },
        { id: 5, materialName: '纸质' }
      ]
    }
  } catch (error) {
    console.error('获取材质数据出错:', error)
    // 如果API失败，使用默认数据
    materialOptions.value = [
      { id: 1, materialName: '金属' },
      { id: 2, materialName: '橡胶' },
      { id: 3, materialName: '塑料' },
      { id: 4, materialName: '液体' },
      { id: 5, materialName: '纸质' }
    ]
  } finally {
    loadingMaterials.value = false
  }
}

// 方法
const handleSearch = () => {
  currentPage.value = 1
  fetchReceivingList()
}

const handleReset = () => {
  searchForm.goodName = ''
  searchForm.materialId = ''
  searchForm.placeofOrigin = ''
  searchForm.payway = ''
  searchForm.registrant = ''
  currentPage.value = 1
  fetchReceivingList()
}

const handleAdd = () => {
  // 跳转到新增页面
  router.push('/AddWarehouseReceiving')
}

const handleEdit = (item: WarehouseReceivingItem) => {
  // 跳转到编辑页面，传递swNo参数
  router.push({
    path: '/UpdateWarehouseReceiving',
    query: { swNo: item.swNo, mode: 'edit' }  // 改为swNo
  })
}

// 删除单个项目
const handleDeleteItem = async (item: WarehouseReceivingItem) => {
  // 检查swNo是否存在
  if (!item.swNo) {
    alert('该记录缺少swNo字段，无法删除')
    return
  }
  
  if (confirm(`确定要删除货物 ${item.goodName} (swNo: ${item.swNo}) 吗？`)) {
    try {
      // 调用封装的API方法删除记录
      const response = await materialApi.deleteWarehouseReceivingManagement(item.swNo)

      if (response.code === 200) {
        alert('删除成功')
        // 重新加载数据
        fetchReceivingList()
      } else {
        alert('删除失败: ' + response.message)
      }
    } catch (error) {
      console.error('删除出错:', error)
      alert('删除出错，请重试')
    }
  }
}

// 移除批量删除方法
// const handleDelete = async () => {
//   const selectedItems = tableData.value.filter(item => item.selected)
//   if (selectedItems.length === 0) {
//     alert('请选择要删除的项目')
//     return
//   }
//   
//   if (confirm(`确定要删除选中的 ${selectedItems.length} 条记录吗？`)) {
//     try {
//       // 提取选中项目的swNo数组
//       const swNos = selectedItems.map(item => item.swNo).filter(swNo => swNo) // 过滤掉空的swNo
//       
//       if (swNos.length === 0) {
//         alert('选中的项目没有有效的swNo，无法删除')
//         return
//       }
//       
//       // 调用批量删除API接口，使用swNo数组
//       const response = await axios.post('http://localhost:5408/api/WarehouseReceiving/DeleteLsitWarehouseReceivingManagement', {
//         swNos: swNos  // 使用swNos字段而不是ids
//       }, {
//         headers: {
//           'Content-Type': 'application/json',
//           'accept': 'text/plain'
//         }
//       })

//       if (response.data.code === 200) {
//         alert('批量删除成功')
//         // 重新加载数据
//         fetchReceivingList()
//       } else {
//         alert('批量删除失败: ' + response.data.message)
//       }
//     } catch (error) {
//       console.error('批量删除出错:', error)
//       alert('批量删除出错，请重试')
//     }
//   }
// }

const handleView = (item: WarehouseReceivingItem) => {
  // 跳转到查看页面，传递swNo参数
  router.push({
    path: '/UpdateWarehouseReceiving',
    query: { swNo: item.swNo, mode: 'view' }  // 改为swNo
  })
}

// 移除全选相关方法
// const handleSelectAll = () => {
//   tableData.value.forEach(item => {
//     item.selected = selectAll.value
//   })
// }

// const handleSelectItem = () => {
//   const selectedCount = tableData.value.filter(item => item.selected).length
//   selectAll.value = selectedCount === tableData.value.length
// }

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    jumpToPage.value = page
    fetchReceivingList()
  }
}

const handleJumpToPage = () => {
  goToPage(jumpToPage.value)
}

// 格式化金额
const formatAmount = (amount: number) => {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchMaterials() // 获取材质数据
  fetchReceivingList()
})
</script>

<style scoped>
.warehouse-receiving {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 搜索区域样式 */
.search-section {
  background: white;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-form {
  display: flex;
  gap: 20px;
  align-items: end;
  flex-wrap: wrap;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 200px;
}

.form-item label {
  font-weight: bold;
  color: #333;
  font-size: 14px;
}

.form-input, .form-select {
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-input:focus, .form-select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
}

.form-actions {
  display: flex;
  gap: 10px;
}

/* 按钮样式 */
.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 5px;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
  transform: translateY(-1px);
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #545b62;
  transform: translateY(-1px);
}

/* 操作按钮区域 */
.action-section {
  background: white;
  padding: 15px 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  gap: 15px;
}

/* 表格样式 */
.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.data-table th {
  background: #f8f9fa;
  font-weight: bold;
  color: #333;
  position: sticky;
  top: 0;
}

.data-table tbody tr:hover {
  background: #f8f9fa;
}

.checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-action {
  padding: 4px 8px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.btn-edit {
  background: #17a2b8;
  color: white;
}

.btn-edit:hover {
  background: #138496;
}

.btn-delete {
  background: #dc3545;
  color: white;
}

.btn-delete:hover {
  background: #c82333;
}

.btn-view {
  background: #6c757d;
  color: white;
}

.btn-view:hover {
  background: #545b62;
}

/* 分页样式 */
.pagination-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
  align-items: center;
}

.btn-pagination {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-pagination:hover:not(.disabled) {
  background: #f8f9fa;
}

.btn-pagination.active {
  background: #28a745;
  color: white;
  border-color: #28a745;
}

.btn-pagination:disabled,
.btn-pagination.disabled {
  background: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.jump-input {
  width: 60px;
  padding: 6px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
}

/* 加载状态样式 */
.loading-cell, .empty-cell {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 16px;
}

.loading-spinner {
  display: inline-block;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 加载提示样式 */
.loading-hint {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
  font-style: italic;
}

/* 图标样式 */
.icon-search::before {
  content: "🔍";
}

.icon-refresh::before {
  content: "🔄";
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .form-item {
    min-width: auto;
  }
  
  .action-section {
    flex-wrap: wrap;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 15px;
  }
}

@media (max-width: 768px) {
  .warehouse-receiving {
    padding: 10px;
  }
  
  .data-table {
    font-size: 12px;
  }
  
  .data-table th,
  .data-table td {
    padding: 8px 4px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}
</style>
